# -*- coding: utf-8 -*-
#linkparse.py
"""用于解析lnk文件，提取lnk对应的文件路径。获取系统部分路径。获取exe文件的图标
"""
import os

import pythoncom
from win32com.shell import shell
from win32com.shell import shellcon


def GetpathFromLink(lnkpath):
    """用于解析lnk文件，提取lnk对应的文件路径
    lnkpath 必须为unicode,返回的地址也是unicode
    """
    try:
        shortcut = pythoncom.CoCreateInstance(
            shell.CLSID_ShellLink, None,
            pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
        shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load(lnkpath)
        path = shortcut.GetPath(shell.SLGP_SHORTPATH)[0]
        return path.decode('gbk')
    except:
        return ''


def CreateLnkpath(filename, lnkname):
    shortcut = pythoncom.CoCreateInstance(
        shell.CLSID_ShellLink, None,
        pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
    shortcut.SetPath(filename)
    if os.path.splitext(lnkname)[-1] != '.lnk':
        lnkname += ".lnk"
    shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)

def GetURLFromShortcut(url):
    shortcut = pythoncom.CoCreateInstance(
        shell.CLSID_InternetShortcut,None,
        pythoncom.CLSCTX_INPROC_SERVER,shell.IID_IUniformResourceLocator)
    shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(url)
    url = shortcut.GetURL()

    return url

def CreateURLShortcut(url,name):
    shortcut = pythoncom.CoCreateInstance(
        shell.CLSID_InternetShortcut,None,
        pythoncom.CLSCTX_INPROC_SERVER,shell.IID_IUniformResourceLocator)
    shortcut.SetURL(url)
    if os.path.splitext(name)[-1] != '.url':
        name += '.url'
    shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(name,0)

def GetSystemPath(csidl):
    ''' 获取系统的一些目录路径，调用方法：GetSystemPath('CSIDL_ADMINTOOLS')
    返回unicode格式地址
    CSIDL_ADMINTOOLS As Long = &H30                '（用户）\开始菜单\程序\系统管理工具
    CSIDL_ALTSTARTUP As Long = &H1D                '未本地化的启动
    CSIDL_APPDATA As Long = &H1A                   '（用户）\应用程序的数据
    CSIDL_BITBUCKET As Long = &HA                  '（桌面）\回收站
    CSIDL_CONTROLS As Long = &H3                   '我的电脑\控制面板
    CSIDL_COOKIES As Long = &H21
    CSIDL_DESKTOP As Long = &H0                    '桌面
    CSIDL_DESKTOPDIRECTORY As Long = &H10          '（用户）\桌面
    CSIDL_FAVORITES As Long = &H6                  '（用户）\个性化设置
    CSIDL_FONTS As Long = &H14                     'windows\字体
    CSIDL_HISTORY As Long = &H22
    CSIDL_INTERNET As Long = &H1                   'IE（桌面上的图标
    CSIDL_INTERNET_CACHE As Long = &H20            '因特网缓存文件夹
    CSIDL_LOCAL_APPDATA     As Long = &H1C            '（用户）\本地设置\应用程序数据
    CSIDL_DRIVES As Long = &H11                    '我的电脑
    CSIDL_MYPICTURES As Long = &H27                'C:\Program Files\My Pictures
    CSIDL_NETHOOD As Long = &H13                   '（用户）\网上邻居中的元素
    CSIDL_NETWORK As Long = &H12                   '网上邻居
    CSIDL_PRINTERS As Long = &H4                   '我的电脑\打印机
    CSIDL_PRINTHOOD As Long = &H1B                 '（用户）\打印机连接
    CSIDL_PERSONAL As Long = &H5                   '我的文档
    CSIDL_PROGRAM_FILES As Long = &H26             'C:\Program Files
    CSIDL_PROGRAM_FILESX86 As Long = &H2A          'x86 apps (Alpha)的程序文件目录
    CSIDL_PROGRAMS As Long = &H2                   '开始菜单\程序
    CSIDL_PROGRAM_FILES_COMMON As Long = &H2B      'Program Files\Common
    CSIDL_PROGRAM_FILES_COMMONX86 As Long = &H2C 'RISC上的x86 \Program Files\Common
    CSIDL_RECENT As Long = &H8                     '(用户)\最近记录目录
    CSIDL_SENDTO As Long = &H9                     '(用户)\发送到目录
    CSIDL_STARTMENU As Long = &HB                  '(用户)\开始菜单
    CSIDL_STARTUP As Long = &H7                    '开始菜单\程序\启动
    CSIDL_SYSTEM As Long = &H25                    'system文件夹
    CSIDL_SYSTEMX86 As Long = &H29                 'x86 apps (Alpha)的system文件夹
    CSIDL_TEMPLATES As Long = &H15
    CSIDL_PROFILE As Long = &H28                   '用户概貌文件夹
    CSIDL_WINDOWS As Long = &H24                   'Windows目录或SYSROOT()
    CSIDL_COMMON_ADMINTOOLS As Long = &H2F         '（所有用户）\开始菜单\程序\系统管理工具
    CSIDL_COMMON_ALTSTARTUP As Long = &H1E         '未本地化的通用启动
    CSIDL_COMMON_APPDATA As Long = &H23            '（所有用户）\应用程序数据
    CSIDL_COMMON_DESKTOPDIRECTORY As Long = &H19 '（所有用户）\桌面
    CSIDL_COMMON_DOCUMENTS As Long = &H2E          '（所有用户）\文档
    CSIDL_COMMON_FAVORITES As Long = &H1F          '(所有用户)\设置
    CSIDL_COMMON_PROGRAMS As Long = &H17           '(所有用户)\程序
    CSIDL_COMMON_STARTMENU As Long = &H16          '(所有用户)\开始菜单
    CSIDL_COMMON_STARTUP As Long = &H18            '(所有用户)\启动
    CSIDL_COMMON_TEMPLATES As Long = &H2D          '(所有用户)\临时
    '''
    try:
        nFolder = getattr(shellcon, csidl)
        ilist = shell.SHGetSpecialFolderLocation(0, nFolder)
        dtpath = shell.SHGetPathFromIDList(ilist)
    except :
        return None
    dtpath.decode('utf-8')
    return dtpath

def GetDesktopPath():
    '''获取系统桌面路径'''
    ilist = shell.SHGetSpecialFolderLocation(0,shellcon.CSIDL_CONTROLS)
    dtpath = shell.SHGetPathFromIDList(ilist)

    dtpath = dtpath.decode('gbk')
    return dtpath

def ExtractIcon2File(exefile, outputfile):
    '''提取exe文件的图标文件并保存（只提取一个32*32的图标）
    exefile需要unicode格式
    '''
    import win32ui
    import win32gui
    import os
    if not os.path.exists(exefile) or os.path.isdir(exefile):
        return False
    large, small = win32gui.ExtractIconEx(exefile,0)
    if len(small) > 0:
        win32gui.DestroyIcon(small[0])
    if len(large) > 0:
        hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap( hdc, 32, 32 )
        hdc = hdc.CreateCompatibleDC()
        hdc.SelectObject( hbmp )
        hdc.DrawIcon( (0,0), large[0] )
        hbmp.SaveBitmapFile( hdc, outputfile)
        return True
    return False


if __name__ == '__main__':
#    ExtractIcon2File(ur"D:\Program Files\Tencent\QQ+\Bin\QQ.exe", "save.bmp" )
#    print GetSystemPath('CSIDL_COMMON_STARTMENU')
#    print GetpathFromLink(r'D:\快捷\定时关机.lnk'.decode('utf8'))
    print GetpathFromLink(r'D:\快捷\360软件管家.lnk'.decode('utf8'))
    pass


    
